package com.wangsd.member.controller;

import com.gitee.fastmybatis.core.PageInfo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wangsd.common.controller.AjaxResult;
import com.wangsd.common.controller.BaseController;
import com.wangsd.common.jwt.LoginUser;
import com.wangsd.common.jwt.TokenService;
import com.wangsd.common.utils.ServletUtils;
import com.wangsd.member.entity.Member;
import com.wangsd.member.entity.MemberCoupon;
import com.wangsd.member.service.MemberCouponService;
import com.wangsd.member.service.MemberService;
import com.wangsd.system.entity.Coupon;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * 用户Controller
 *
 * @author wsd
 * @date 2021-06-18
 */
@Api(tags = "用户管理")
@RestController
@RequestMapping("/member")
public class MemberController extends BaseController {
    @Autowired
    private MemberService memberService;
    @Autowired
    private MemberCouponService memberCouponService;
    @Autowired
    private TokenService tokenService;

    @ApiOperation(value = "查询用户列表")
    @GetMapping("/list")
    public AjaxResult<PageInfo<Member>> list(Member member) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());

        Page page = PageHelper.startPage(ServletUtils.getParameterToInt("pageNum"), ServletUtils.getParameterToInt("pageSize"));
        List<Member> list = memberService.selectMemberList(member);
        return AjaxResult.success(getPageInfo(page, list));
    }


    @ApiOperation(value = "获取用户详细信息")
    @GetMapping("/{id}")
    public AjaxResult<Member> getInfo(@PathVariable("id") Long id) {
        Member member = memberService.selectMemberById(id);
        return AjaxResult.success(member);
    }

    @ApiOperation(value = "新增/修改用户")
    @PostMapping("/saveOrUpdate")
    public AjaxResult saveOrUpdate(@RequestBody Member member) {
        if (member.getId() == null){
            memberService.insertMember(member);
        } else {
            memberService.updateMember(member);
        }
        return AjaxResult.success("success");
    }


    @ApiOperation(value = "删除用户")
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {
        memberService.deleteMemberById(id);
        return AjaxResult.success("success");
    }

    @ApiOperation(value = "获取用户收银台信息")
    @PostMapping("/getUserCouponInfo")
    public AjaxResult<Member> getInfo(String openid) {
        Member member = memberService.selectMemberByOpenid(openid);
        List<Coupon> memberCouponList = memberCouponService.selectUserCouponList(member.getId(),2);
        HashMap<String, Object> map = new HashMap<>();
        map.put("member",member);
        map.put("couponList",memberCouponList);
        return AjaxResult.success(map);
    }
}
